﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/


using System;
using System.Collections.Generic;

namespace Tesla.Core {
    /// <summary>
    /// EngineServiceProviders is a collection of services used by the engine internally. This
    /// is to provide loose coupling and reduce reliance on singletons. The engine uses service providers
    /// in order to create concrete implementations for many objects at run time, such as hardware buffers
    /// and textures.
    /// </summary>
    public sealed class EngineServiceProviders : IServiceProvider {

        private Dictionary<Type, Object> _services;

        /// <summary>
        /// Event for when a new service type has been added. The new service will be
        /// passed as the sender.
        /// </summary>
        public event EventHandler ServiceAdded;

        /// <summary>
        /// Event for when an existing service type is replaced by a new service
        /// provider of the same type. The new service will be passed as the sender.
        /// </summary>
        public event EventHandler ServiceChanged;

        /// <summary>
        /// Event for when a service type is removed. The service removed will be
        /// passsed as the sender, or null signifying all services have been removed.
        /// </summary>
        public event EventHandler ServiceRemoved;

        /// <summary>
        /// Creates a new instance of an EngineServiceProvider.
        /// </summary>
        public EngineServiceProviders() {
            _services = new Dictionary<Type, Object>();
        }

        /// <summary>
        /// Adds a new service to the provider collection.
        /// </summary>
        /// <param name="type">Type of the service</param>
        /// <param name="provider">Provider object</param>
        /// <exception cref="System.ArgumentNullException">Type or Provider is null</exception>
        /// <exception cref="System.ArgumentException">Provider not assignable to type</exception>
        public void AddService(Type type, Object provider) {
            if(type == null) {
                throw new ArgumentNullException("Service type cannot be null.");
            }

            if(provider == null) {
                throw new ArgumentNullException("Service provider cannot be null.");
            }

            if(!type.IsAssignableFrom(provider.GetType())) {
                throw new ArgumentException("Service provider must be assignable to type.");
            }

            if(_services.ContainsKey(type)) {
                _services[type] = provider;
                OnServiceChanged(provider);
            } else {
                _services.Add(type, provider);
                OnServiceAdded(provider);
            }
        }

        /// <summary>
        /// Gets a service from the provider collection.
        /// </summary>
        /// <param name="type">Provider type</param>
        /// <returns>Returns the service</returns>
        /// <exception cref="System.ArgumentNullException">If service type is null</exception>
        public Object GetService(Type type) {
            if(type == null) {
                throw new ArgumentNullException("Service type cannot be null.");
            }

            Object value;
            if(_services.TryGetValue(type, out value)) {
                return value;
            }
            return null;
        }

        /// <summary>
        /// Gets a service from the provider collection. Equivalent to GetService(typeof(T))
        /// </summary>
        /// <typeparam name="T">Service interface</typeparam>
        /// <returns>Returns the service</returns>
        public T GetService<T>() {
            return (T) GetService(typeof(T));
        }

        /// <summary>
        /// Removes a service from the provider collection.
        /// </summary>
        /// <param name="type">Type of service to remove</param>
        /// <exception cref="System.ArgumentNullException">If service type is null</exception>
        public void RemoveService(Type type) {
            if(type == null) {
                throw new ArgumentNullException("Service type cannot be null.");
            }

            Object service;
            if(_services.TryGetValue(type, out service)) {
                _services.Remove(type);
                OnServiceRemoved(service);
            }
        }

        /// <summary>
        /// Removes all services from the provider collection.
        /// </summary>
        public void RemoveAll() {
            _services.Clear();
            OnServiceRemoved(null);
        }

        /// <summary>
        /// Disposes all providers that implement IDisposable and remove the services.
        /// </summary>
        public void DisposeAndRemoveAll() {
            foreach(KeyValuePair<Type, Object> kv in _services) {
                IDisposable disposable = kv.Value as IDisposable;
                if(disposable != null) {
                    disposable.Dispose();
                }
            }
            RemoveAll();
        }

        private void OnServiceAdded(Object service) {
            if(ServiceAdded != null) {
                ServiceAdded(service, EventArgs.Empty);
            }
        }

        private void OnServiceChanged(Object service) {
            if(ServiceChanged != null) {
                ServiceChanged(service, EventArgs.Empty);
            }
        }

        private void OnServiceRemoved(Object service) {
            if(ServiceRemoved != null) {
                ServiceRemoved(service, EventArgs.Empty);
            }
        }
    }
}
